<template>
  <div>
<van-list
  v-model="loading"
  :finished="finished"
  finished-text="没有更多了"
  @load="onLoad"
  :immediate-check="false"
>

  <!-- <van-cell v-for="(item,index) in list" :key="index" :title="item.content" /> -->
  <CommentItem v-for="(item,index) in list" :key="index" :comment="item"
  @reply-click="$emit('reply-click',$event)"></CommentItem>
</van-list>
  </div>
</template>

<script>
import { getComments } from '@/api/comment.js'
import CommentItem from './comment-item.vue'
import eventBus from '@/utils/eventBus.js'
export default {
  name: 'CommentList',
  props: {
    // 将article.id改为source，可以适配两种情况
    source: [String, Number, Object],
    list: {
      // 将兄弟组件的数据拿到父组件里面去
      type: Array,
      default: () => []
    },
    // 增加type,适配两种情况
    type: {
      type: String,
      default: 'a',
      validator (val) {
        return ['a', 'c'].includes(val)
      }
    }
  },
  components: { CommentItem },
  data () {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null
    }
  },
  created () {
    this.onLoad()
    eventBus.$on('onPostSuccess', () => {
      this.onLoad()
    })
  },
  mounted () {

  },
  methods: {
    async onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
    //   setTimeout(() => {
    //     for (let i = 0; i < 10; i++) {
    //       this.list.push(this.list.length + 1)
    //     }

      //     // 加载状态结束
      //     this.loading = false

      //     // 数据全部加载完成
      //     if (this.list.length >= 40) {
      //       this.finished = true
      //     }
      //   }, 1000)
      // 1.发请求
      const { data: { data: { last_id: offset, results, total_count: totalCount } } } = await getComments({
        type: this.type,
        source: this.source,
        offset: this.offset,
        limit: 20
      })
      //   2.添加数据到list
      this.list.push(...results)
      //   3.设置loading
      this.loading = false
      //   4.判断是否结束
      if (results.length === 0) {
        this.finished = true
      }
      //   5.设置页码值
      this.offset = offset
      this.$emit('set-totalCount', totalCount)
    }
  }
}
</script>

<style>

</style>